package com.wnxy.portal.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wnxy.portal.common.exception.Asserts;
import com.wnxy.portal.common.result.Result;
import com.wnxy.portal.common.result.impl.BusinessCodeEnum;
import com.wnxy.portal.entity.User;
import com.wnxy.portal.mapper.UserMapper;
import com.wnxy.portal.model.dto.RegisterDTO;
import com.wnxy.portal.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Jet
 * @since 2023-12-11
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public User login(String name, String password) {
        return this.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getAccount,name)
                .eq(User::getPassword,password).last("limit 1"));
    }

    @Override
    public void register(RegisterDTO registerDTO) {
        //1、校验密码与确认密码、验证码
        Asserts.error(!registerDTO.getPassword().equals(registerDTO.getCheckPass()), BusinessCodeEnum.PWD_VALIDATE_FAILED);
        String redisCode = stringRedisTemplate.opsForValue().get(registerDTO.getEmail());
        Asserts.error(!registerDTO.getValicode().equals(redisCode),BusinessCodeEnum.VERRIFY_CODE_ERROR);

        //2、账号唯一性校验
        long count = this.count(Wrappers.lambdaQuery(User.class).eq(User::getAccount,registerDTO.getAccount()).last("limit 1"));
        Asserts.error(count>0,BusinessCodeEnum.ACCOUNT_EXISTS);

        //3、邮箱唯一性校验
        long emailCount = this.count(Wrappers.lambdaQuery(User.class).eq(User::getEmail,registerDTO.getEmail()).last("limit 1"));
        Asserts.error(emailCount>0,BusinessCodeEnum.EMAIL_EXISTS);

        //4、保存用户
        User user = BeanUtil.copyProperties(registerDTO, User.class);
        user.setState(1);
        user.setCreatetime(new Date());
        user.setUpdatetime(new Date());
        user.setNickname(RandomUtil.randomString(6));
        this.save(user);
    }
}
